<template>
  <a-spin :spinning="loading">
    <JFormContainer :disabled="disabled">
      <template #detail>
        <a-form v-bind="formItemLayout" name="ExamQuestionsForm" ref="formRef">
          <a-row>
						<!-- <a-col :span="24">
							<a-form-item label="题库ID" v-bind="validateInfos.bankId" id="ExamQuestionsForm-bankId" name="bankId">
								<a-input-number v-model:value="formData.bankId" placeholder="请输入题库ID" style="width: 100%" />
							</a-form-item>
						</a-col> -->
            <a-col :span="24">
							<a-form-item label="题目类型">
              赋分题
							</a-form-item>
						</a-col>
						<a-col :span="24">
							<a-form-item label="题目内容" v-bind="validateInfos.content" id="ExamQuestionsForm-content" name="content">
								<a-textarea v-model:value="formData.content" :rows="4" placeholder="请输入题目内容" />
							</a-form-item>
						</a-col>
						<a-col :span="24">
							<a-form-item label="是否为多选题" v-bind="validateInfos.isMultipleChoice" id="ExamQuestionsForm-isMultipleChoice" name="isMultipleChoice">
                <a-select
                 placeholder="请选择题目类型是否多选"
                  ref="select"
                  v-model:value="formData.isMultipleChoice"
                >
                  <a-select-option :value="1">多选题</a-select-option>
                  <a-select-option :value="0">单选题</a-select-option>
                </a-select>
								<!-- <a-input-number v-model:value="formData.isMultipleChoice" placeholder="请输入是否为多选题 (布尔值)" style="width: 100%" /> -->
							</a-form-item>
						</a-col>
            <!-- <a-col :span="24">
							<a-form-item label="题目类型" v-bind="validateInfos.isPublic" id="ExamQuestionsForm-isMultipleChoice" name="isPublic">
                <a-select
                 placeholder="请选择题目类型"
                  ref="select"
                  v-model:value="formData.isPublic"
                >
                <a-select-option :value="1">基础信息题</a-select-option>
                  <a-select-option :value="0">计分题</a-select-option>
                  <a-select-option :value="2">调查问卷题</a-select-option>
                  <a-select-option :value="3">关联题</a-select-option>
                </a-select>
							</a-form-item>
						</a-col> -->
						<!-- <a-col :span="24">
							<a-form-item label="题目分值" v-bind="validateInfos.valueOfScore" id="ExamQuestionsForm-valueOfScore" name="valueOfScore">
								<a-input-number v-model:value="formData.valueOfScore"  placeholder="请输入题目分值" style="width: 100%" />
							</a-form-item>
						</a-col> -->
						<!-- 去掉正确答案输入框 -->
          </a-row>
        </a-form>
      </template>
    </JFormContainer>

		<!-- 子表单区域 -->
    <a-tabs v-model:activeKey="activeKey" animated>
      <a-tab-pane tab="exam_options（答案选项内容）" key="examOptions" :forceRender="true">
        <j-vxe-table
          :keep-source="true"
          resizable
          ref="examOptionsTableRef"
          :loading="examOptionsTable.loading"
          :columns="examOptionsTable.columns"
          :dataSource="examOptionsTable.dataSource"
          :height="340"
          :disabled="disabled"
          :rowNumber="true"
          :rowSelection="true"
          :toolbar="true"
          @valueChange="handleOptionsValueChange"/>
      </a-tab-pane>
    </a-tabs>
  </a-spin>
</template>

<script lang="ts">
  import { defineComponent,watch , ref, reactive, computed, toRaw, onMounted,nextTick } from 'vue';
  import { defHttp } from '/@/utils/http/axios';
  import { useValidateAntFormAndTable } from '/@/hooks/system/useJvxeMethods';
  import { queryExamOptionsListByMainId, queryDataById, saveOrUpdate,lists } from '../ExamQuestions.api';
  import { JVxeTable } from '/@/components/jeecg/JVxeTable';
  import {examOptionsColumns} from '../ExamQuestions.data';
  import JFormContainer from '/@/components/Form/src/container/JFormContainer.vue';
  import { Form,message } from 'ant-design-vue';
  const useForm = Form.useForm;

  export default defineComponent({
    name: "ExamQuestionsForm",
    components:{
      JVxeTable,
			JFormContainer,
    },
    props:{
      formDisabled:{
        type: Boolean,
        default: false
      },
      par_id:Number,
      formData: { type: Object, default: ()=>{} },
      formBpm: { type: Boolean, default: true }
    },
    emits:['success'],
    setup(props, {emit}) {
      
      // let examOptionsTable = reactive({})
       // 在 onMounted 中初始化数据
       let examOptionsTable  = reactive<Record<string, any>>({
              loading: false,
              columns: examOptionsColumns,
              dataSource: []
            });
      // 等待所有的 API 调用和数据更新完成
      for (const item of examOptionsColumns) {
        if (item.title === '关联题目') {
          // 改成表单传值的方式，不在初始化时直接调用
          // lists({bankid:props.par_id}).then(res=>{
          //   item.options = res
          //   examOptionsTable.columns = [...examOptionsColumns]
          // });
        }
      }
      const par_ids = ref()
      par_ids.value = props.par_id 
      const loading = ref(false);
      const formRef = ref();
      const examOptionsTableRef = ref();
      // examOptionsColumns.forEach(async item =>{
      //     if(item.title === '关联题目'){
      //       const listss = await lists()
      //       console.log(listss,"listss")
      //       item.options = listss
      //       // await nextTick();  // 确保更新完成后执行
      //     }
      // })
      
      const activeKey = ref('examOptions');
      const formData = reactive<Record<string, any>>({
        id: '',
        bankId: undefined,
        content: '',   
        isMultipleChoice: undefined,
        isPublic:4,
        valueOfScore: undefined,
        correctAnswer: '',   // 保留这个字段用于后端，但不在界面上显示
        other: '',   
        other2: '',   
      });
      // Watcher for formData.isPublic
      watch(() => formData.isPublic, (newValue) => {
        if (newValue === 3) {
          formData.isMultipleChoice = 0
          formData.valueOfScore = ''; // Clear the score
          formData.correctAnswer = ''; // Clear the correct answer
        }
        if (newValue === 1) {
          formData.valueOfScore = 0; // Clear the score
          formData.correctAnswer = ''; // Clear the correct answer
        }
        if (newValue === 2) {
          formData.valueOfScore = 0; // Clear the score
          formData.correctAnswer = ''; // Clear the correct answer
        }
      });
      // 当是否多选切换时，重新计算正确答案
      watch(() => formData.isMultipleChoice, (newValue, oldValue) => {
        // 如果从多选切换到单选，且当前有多个正确选项，只保留第一个
        if (oldValue === 1 && newValue === 0) {
          const rows = (examOptionsTableRef.value && examOptionsTableRef.value.getTableData)
            ? examOptionsTableRef.value.getTableData()
            : (examOptionsTable.dataSource || []);
          const selected = rows.filter((r:any) => String(r.isCorrect) === '1');
          if (selected.length > 1) {
            // 只保留第一个正确选项
            rows.forEach((row:any, index:any) => {
              if (index === 0) {
                row.isCorrect = '1';
              } else {
                row.isCorrect = '0';
              }
            });
            message.warning('已切换到单选题，只保留第一个正确选项！');
          }
        }
        updateCorrectAnswerFromOptions();
      });

      // 监听bankId变化，自动调用lists接口
      watch(() => formData.bankId, (newValue) => {
        if (newValue) {
          // 当bankId变化时，调用lists接口获取关联题目列表
          callListsWithFormData();
        }
      });
      if(props.par_id){
        formData.bankId = props.par_id
      }
      //表单验证
      const validatorRules = reactive({
        // bankId: [{ required: true, message: '请输入题库ID!'},],
        content: [{ required: true, message: '请输入题目内容!'},],
        isMultipleChoice: [{ required: true, message: '请选择是多选还是单选题'},],
        isPublic: [{ required: true, message: '请选择题目类型'},],
      });
      const {resetFields, validate, validateInfos} = useForm(formData, validatorRules, {immediate: false});
      const dbData = {};
      const formItemLayout = {
        labelCol: {xs: {span: 24}, sm: {span: 5}},
        wrapperCol: {xs: {span: 24}, sm: {span: 16}},
      };

      // 表单禁用
      const disabled = computed(()=>{
        if(props.formBpm === true){
          if(props.formData.disabled === false){
            return false;
          }else{
            return true;
          }
        }
        return props.formDisabled;
      });

      

      function add() {
        resetFields();
        examOptionsTable.dataSource = [];
      }

      async function edit(row) {
        //主表数据
        await queryMainData(row.id);
        //子表数据
        const examOptionsDataList = await queryExamOptionsListByMainId(row['id']);
        examOptionsTable.dataSource = [...examOptionsDataList];
      }

      async function queryMainData(id) {
        const row = await queryDataById(id);
        resetFields();
        const tmpData = {};
        Object.keys(formData).forEach((key) => {
          if(row.hasOwnProperty(key)){
            tmpData[key] = row[key]
          }
        })
        //赋值
        Object.assign(formData,tmpData);
      }

      const {getSubFormAndTableData, transformData} = useValidateAntFormAndTable(activeKey, {
        'examOptions': examOptionsTableRef,
      });

      async function getFormData() {
        try {
          // 触发表单验证
          await validate();
        } catch ({ errorFields }) {
          if (errorFields) {
            const firstField = errorFields[0];
            if (firstField) {
              formRef.value.scrollToField(firstField.name, { behavior: 'smooth', block: 'center' });
            }
          }
          return Promise.reject(errorFields);
        }
        return transformData(toRaw(formData))
      }

      async function submitForm() {
        const mainData = await getFormData();
        const subData = await getSubFormAndTableData();
        // console.log(dbData,"dbData")
        // console.log(mainData,"mainData")
        console.log(subData,"subData")
        let items = subData.examOptionsList.filter(item=>item.isCorrect == 1)//下面的表格返回的数据大于1条多选
        
        // 验证必须选择正确答案
        // if(items.length === 0){
        //   message.warning('请至少选择一个正确答案！');
        //   return;
        // }
        
        // 验证单选题只能选择一个正确答案
        // if(formData.isMultipleChoice == 0 && items.length > 1){
        //   message.warning('单选题只能选择一个正确答案！');
        //   return;
        // }
        
        // 验证多选题至少选择两个正确答案
        // if(formData.isMultipleChoice == 1 && items.length < 2){
        //   message.warning('多选题至少需要选择两个正确答案！');
        //   return;
        // }
        
        // 自动设置正确答案字段
        // if(formData.isMultipleChoice == 1) {
        //   // 多选题，用逗号分隔
        //   const nums = items.map((r:any) => r.number).filter(Boolean);
        //   formData.correctAnswer = nums.join(',');
        // } else {
        //   // 单选题，只取第一个
        //   formData.correctAnswer = items[0].number || '';
        // }
        
        if(subData.examOptionsList){
          if(subData.examOptionsList.length > 0){
            subData.examOptionsList.forEach((item:any,index:any)=>{
              item['bankId'] = props.par_id 
            })
          }
        }
        
        
        const values = Object.assign({}, dbData, mainData, subData);
        console.log('表单提交数据', values)
        const isUpdate = values.id ? true : false
        await saveOrUpdate(values, isUpdate);
        //关闭弹窗
        emit('success');
      }
      
      function setFieldsValue(values) {
        if(values){
          Object.keys(values).map(k=>{
            formData[k] = values[k];
          });
        }
      }

      /**
       * 值改变事件触发-树控件回调
       * @param key
       * @param value
       */
      function handleFormChange(key, value) {
        formData[key] = value;
      }

      // 根据子表当前勾选的正确选项，自动回填主表正确答案
      function updateCorrectAnswerFromOptions() {
        const rows = (examOptionsTableRef.value && examOptionsTableRef.value.getTableData)
          ? examOptionsTableRef.value.getTableData()
          : (examOptionsTable.dataSource || []);
        const selected = rows.filter((r:any) => String(r.isCorrect) === '1');
        if (formData.isMultipleChoice == 1) {
          const nums = selected.map((r:any) => r.number).filter(Boolean);
          formData.correctAnswer = nums.join(',');
        } else {
          formData.correctAnswer = selected.length > 0 ? (selected[0].number || '') : '';
        }
      }

      // 处理表单传值调用lists接口
      async function handleFormSubmit() {
        try {
          // 如果需要调用lists接口，可以在这里处理
          // const result = await lists({bankid: formData.bankId});
          // 处理返回结果
          
          // 然后调用原有的提交逻辑
          await submitForm();
        } catch (error) {
          console.error('表单提交失败:', error);
          message.error('表单提交失败，请重试');
        }
      }

      // 根据表单数据调用lists接口
      async function callListsWithFormData() {
        try {
          // 使用表单中的bankId调用lists接口
          if (formData.bankId) {
            const result = await lists({bankid: formData.bankId});
            console.log('lists接口返回结果:', result);
            
            // 更新表格列配置中的选项
            for (const item of examOptionsTable.columns) {
              if (item.title === '关联题目') {
                item.options = result;
                break;
              }
            }
            
            return result;
          }
        } catch (error) {
          console.error('调用lists接口失败:', error);
          message.error('获取关联题目列表失败');
        }
      }

      // 监听子表单元格变更（正确选项/序列号）同步主表正确答案
      function handleOptionsValueChange(e:any) {
        const key = (e && e.col && e.col.key) || (e && e.column && e.column.key);
        if (!key || key === 'isCorrect' || key === 'number') {
          // 如果是单选题，确保只能选择一个正确答案
          if (formData.isMultipleChoice == 0 && key === 'isCorrect') {
            const rows = (examOptionsTableRef.value && examOptionsTableRef.value.getTableData)
              ? examOptionsTableRef.value.getTableData()
              : (examOptionsTable.dataSource || []);
            const selected = rows.filter((r:any) => String(r.isCorrect) === '1');
            if (selected.length > 1) {
              // 如果选择了多个，只保留最后一个
              const currentRow = e.row;
              rows.forEach((row:any) => {
                if (row !== currentRow) {
                  row.isCorrect = '0';
                }
              });
              message.warning('单选题只能选择一个正确答案！');
            }
          }
          updateCorrectAnswerFromOptions();
        }
      }


      return {
        examOptionsTableRef,
        examOptionsTable,
        validatorRules,
        validateInfos,
        par_ids,
        activeKey,
        loading,
        formData,
        setFieldsValue,
        handleFormChange,
        handleOptionsValueChange,
        formItemLayout,
        disabled,
        getFormData,
        submitForm,
        handleFormSubmit, // 新增的表单传值处理方法
        callListsWithFormData, // 新增的根据表单数据调用lists接口的方法
        add,
        edit,
        formRef,
      }
    }
  });
</script>
<style lang="less" scoped></style>
